<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-row :gutter="48">
          <a-col :span="12">
            <a-form-model-item label="款项名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="paymentName">

              <a-select
                v-model="model.paymentName"
                :disabled="formDisabled"
                placeholder="请选择款项名称"
                :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
              >
                <a-select-option v-for="item in paymentNameList" :key="item.id" :value="item.id">
                  {{ item.nodeName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="应收金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="amountReceivable">
              <a-input-number
                :disabled="formDisabled"
                :max="999999999"
                :min="0"
                :precision="2"
                v-model="model.amountReceivable"
                placeholder="请输入应收金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="豁免类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exemptionType">
              <j-dict-select-tag
                :disabled="formDisabled"
                type="list"
                v-model="model.exemptionType"
                dictCode="exemption_type"
                @blur="exemptionTypeHandler"
                placeholder="请选择豁免类型"/>
            </a-form-model-item>
          </a-col>

          <template v-if="model.exemptionType === '1'">
            <a-col :span="12" >
              <!--              豁免经营团队-->
              <a-form-model-item label="豁免对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exemptionManagementTeam">
                <select-team-input
                  v-model="model.exemptionManagementTeam"
                  :tdlx="1"
                  disabled
                />
              </a-form-model-item>
            </a-col>
          </template>

          <template v-if="model.exemptionType === '2'">
            <a-col :span="12">
              <!-- 豁免项目承接人  -->
              <a-form-model-item label="豁免对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exemptionUndertaker">
                <select-user-by-dep :multi="false" v-model="model.exemptionUndertaker" disabled></select-user-by-dep>
              </a-form-model-item>
            </a-col>
          </template>

          <template v-if="model.exemptionType === '3'">
            <a-col :span="12">
              <!-- 豁免项目负责人-->
              <a-form-model-item label="豁免对象" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exemptionProjectHead">
                <a-select
                  mode="multiple"
                  v-model="exemptionProjectHeadLi"
                  :disabled="formDisabled"
                  placeholder="请选择选择豁免对象"
                  :getPopupContainer="triggerNode => {return triggerNode.parentNode}"
                >
                  <a-select-option v-for="item in exemptionProjectHeadList" :key="item.id" :value="item.id">
                    {{ item.name }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
          </template>
          <a-col :span="12">
            <a-form-model-item label="豁免考核月份" :labelCol="labelCol" :wrapperCol="wrapperCol" required>
              <a-col :span="12">
                <a-form-model-item prop="exemptionDateBegin">
                  <a-month-picker v-model="model.exemptionDateBegin" placeholder="起始月份" @change="startDateHandle" />
                </a-form-model-item>
              </a-col>
              <a-col :span="12">
                <a-form-model-item prop="exemptionDateEnd">
                  <a-month-picker v-model="model.exemptionDateEnd" placeholder="结束月份" @change="endDateHandle" />
                </a-form-model-item>
              </a-col>

            </a-form-model-item>
          </a-col>
          <a-col :span="12">
            <a-form-model-item label="豁免罚款金额（元）" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="exemptionPenaltyAmount">
              <a-input-number
                :disabled="formDisabled"
                :max="999999999"
                :min="0"
                :precision="2"
                v-model="model.exemptionPenaltyAmount"
                placeholder="请输入豁免罚款金额"
                style="width: 100%" />
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>

  import { getAction } from '@/api/manage'
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep'
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput'
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput'
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput'
  import moment from 'moment'
  import { mapGetters } from 'vuex'
  import { filterMultiDictText, initDictOptions } from '@/components/dict/JDictSelectUtil'
  export default {
    name: 'PaybackDisclaimerDisclaimerInfoForm',
    components: {
      SelectUserByDep,
      SelectTeamInput,
      SelectCompanyInput,
      SelectCustomerInput
    },
    props: {
      // 表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      contractId: {
        type: String,
        default: '',
        required: false
      },
      projectId: {
        type: String,
        default: '',
        required: false
      },
      managementTeam: {
        type: String,
        default: '',
        required: false
      },
      undertaker: {
        type: String,
        default: '',
        required: false
      }
    },
    data () {
      return {
        model: {},
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 }
        },
        confirmLoading: false,
        validatorRules: {
          paymentName: [
            { required: true, message: '请选择款项名称!' }
          ],
          amountReceivable: [
            { required: true, pattern: /^(([1-9][0-9]*)|([0]\.\d{0,2}|[1-9][0-9]*\.\d{0,2}))$/, message: '请输入应收金额!' }
          ],
          exemptionType: [
            { required: true, message: '请选择豁免类型!' }
          ],
          exemptionDateBegin: [
            { required: true, message: '请选择豁免考核起始月份!', trigger: 'change' }
          ],
          exemptionDateEnd: [
            { required: true, message: '请选择豁免考核结束月份!', trigger: 'change' }
          ],
          exemptionPenaltyAmount: [
            { required: true, message: '请输入豁免罚款金额!' }
          ]

        },
        url: {
          add: '/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/add',
          edit: '/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/edit',
          queryById: '/api/erp/audit/paybackDisclaimer/paybackDisclaimerDisclaimerInfo/queryById',
          queryPaymentNode: '/api/erp/progress/erpProgressPaymentNode/queryListByContractId',
          queryProjectTaskFinal: '/api/erp/omc/project/erpOmcProjectTaskFinal/queryPageList' // 任务档案-用于查询项目负责人列表
        },
        paymentNameList: [],
        exemptionProjectHeadList: [],
        flag: false,
        exemptionProjectHeadLi: [],
        dictOptions: {}
      }
    },
    computed: {
      formDisabled() {
        return this.disabled
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 初始化选择列表数据
      this.getExemptionType()
      // 加载数据字典信息
      this.initDictConfig();
    },
    mounted() {

    },
    methods: {
      ...mapGetters(['userInfo']),
      moment,
      async initDictConfig() {
        // 人员
        initDictOptions('erp_employee_file,name,id').then(async(res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'empId', res.result)
          }
        })
      },
      add () {
        // 清空选择项目负责人数组
        this.exemptionProjectHeadLi = []
        this.edit(this.modelDefault);
        this.getExemptionType()
      },
      edit (record) {
        this.$refs.form.resetFields();
        this.model = Object.assign({}, record);
        // 项目负责人多选框回显
        this.reShowProjectHead();
        this.visible = true;
      },
      // 处理项目负责人多选框回显问题
      reShowProjectHead() {
        if (this.model.exemptionProjectHead) {
          this.exemptionProjectHeadLi = this.model.exemptionProjectHead.split(',') // 回显数组
        }
      },
      // 获取豁免类型列表
      getExemptionType() {
        getAction(this.url.queryPaymentNode, { contractId: this.contractId }).then((res) => {
          if (res.success) {
            this.paymentNameList = []
            res.result.forEach((item) => {
              this.paymentNameList.push({ 'id': item.id, 'nodeName': item.nodeName })
            })
          } else {
            this.$message.warning(res.message)
          }
        })

        // 初始化豁免对象-项目负责人列表
        getAction(this.url.queryProjectTaskFinal, { projectId: this.projectId }).then((res) => {
          if (res.success) {
            if (res.result.records.length > 0) {
              let projectLeadingTemp = []

              res.result.records.forEach(item => {
                if (item.projectLeading) {
                  projectLeadingTemp.push({ id: item.projectLeading, name: filterMultiDictText(this.dictOptions['empId'], item.projectLeading + '') })
                }
              })
              const uniqueArray = Array.from(new Set(projectLeadingTemp.map(item => JSON.stringify(item))))
                .map(item => JSON.parse(item));
              // console.log('去重后的数组对象',uniqueArray)
              this.exemptionProjectHeadList = uniqueArray
            }
          }
        })
      },

      exemptionTypeHandler(value) {
        if (value) {
          if (value === '1') {
            this.$nextTick(() => {
              console.log('主表的经营团队为：')
              this.$set(this.model, 'exemptionManagementTeam', this.managementTeam)

              // 清空其他数据
              this.$set(this.model, 'exemptionUndertaker', null)
              this.$set(this.model, 'exemptionProjectHead', undefined)
              // this.$set(this.model,'exemptionProjectHeadId',null)
            })
          }
          if (value === '2') {
            this.$nextTick(() => {
              this.$set(this.model, 'exemptionUndertaker', this.undertaker)
              // 清空其他数据
              this.$set(this.model, 'exemptionManagementTeam', null)
              this.$set(this.model, 'exemptionProjectHead', undefined)
              // this.$set(this.model,'exemptionProjectHeadId',null)
            })
          }
          if (value === '3') {
            this.$nextTick(() => {
              // 切换时清空选择项目负责人数据
              this.exemptionProjectHeadLi = []
              // 清空其他数据
              this.$set(this.model, 'exemptionManagementTeam', null)
              this.$set(this.model, 'exemptionUndertaker', null)
            })
          }
        }
      },

      // 豁免开始时间选择回调
      startDateHandle(date, dateString) {
        this.$set(this.model, 'exemptionDateBegin', dateString)
      },
      // 豁免结束时间选择回调
      endDateHandle(date, dateString) {
        this.$set(this.model, 'exemptionDateEnd', dateString)
      },

      submitForm () {
        if (this.model.exemptionDateBegin && this.model.exemptionDateEnd) {
          let diff = moment(this.model.exemptionDateEnd).diff(this.model.exemptionDateBegin, 'month') + 1
          if (diff <= 0) {
            this.$message.warning('豁免考核月份开始月份不可大于结束月份！')
            this.$emit('unButtonDisable')
            return
          }
          if (diff > 3) {
            this.$message.warning('豁免考核月份不可大于三个月！')
            this.$emit('unButtonDisable')
            return
          }
        }

        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            // 字符串逗号拼接
            if (that.exemptionProjectHeadLi && that.exemptionProjectHeadLi.length > 0) {
              let temp = that.exemptionProjectHeadLi.join(',')
              that.$set(that.model, 'exemptionProjectHead', temp)
              that.model.exemptionProjectHead = temp
            }
            let data = JSON.stringify(that.model)
            that.$emit('ok', JSON.parse(data), this.flag);
          } else {
            that.$emit('unButtonDisable');
          }
        })
      }
    }
  }
</script>
